package com.tc.itfarm.admin.biz;

import com.google.common.collect.Lists;
import com.tc.itfarm.admin.vo.ArticleVO;
import com.tc.itfarm.api.util.DateUtils;
import com.tc.itfarm.model.Article;
import com.tc.itfarm.model.Category;
import com.tc.itfarm.model.User;
import com.tc.itfarm.service.ArticleService;
import com.tc.itfarm.service.CategoryService;
import com.tc.itfarm.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

@Service
public class ArticleBiz {
	
	@Resource
	private UserService userService;
	@Resource
	private CategoryService categoryService;
	@Resource
	private ArticleService articleService;
	
	public List<ArticleVO> getArticleVOs (List<Article> articles, HttpServletRequest request) {
		List<ArticleVO> articleVOs = Lists.newArrayList();
		for (Article article : articles) {
			ArticleVO vo = new ArticleVO();
			User user = userService.select(article.getAuthorId());
			vo.setCategoryName("未分类");
			if (article.getTypeId() != -1) {
				Category category = categoryService.select(article.getTypeId());
				vo.setCategoryName(category.getName());
			}
			vo.setArticle(article);
			vo.setAuthorName(user.getNickname());
			vo.setLastDate(DateUtils.dateToChineseString(article.getModifyTime()));
			// 判断图片是否存在
			File file = new File(request.getSession().getServletContext()
					.getRealPath("/titleImg/") + "/" + article.getTitleImg());
			vo.setTitleImgIsExist(file.isFile());
			
			articleVOs.add(vo);
		}
		return articleVOs;
	}
	
	public ArticleVO getArticleVOById(Integer recordId) {
		Article article = articleService.select(recordId);
		article.setPageView(article.getPageView() == null ? 1 : (article.getPageView() + 1));
		articleService.save(article, null);
		ArticleVO vo = new ArticleVO();
		// 查询作者
		User user = userService.select(article.getAuthorId());
		// 分类
		Category category = categoryService.select(article.getTypeId());
		// 查询上条和下条
		vo.setLast(articleService.selectLast(article.getTitle()));
		vo.setNext(articleService.selectNext(article.getTitle()));
		vo.setArticle(article);
		vo.setAuthorName(user.getNickname());
		vo.setCategoryName(category.getName());
		vo.setLastDate(DateUtils.dateToChineseString(article.getModifyTime()));
		return vo;
	}
	
	/**
	 * 生成保存图片名
	 * @param sourceName
	 * @return
	 */
	public String getImgFileName (String sourceName) {
		StringBuilder sb = new StringBuilder();
		sb.append(System.currentTimeMillis()).append((int)Math.random() * 100);
		sourceName = sourceName.substring(sourceName.lastIndexOf(".") + 1);
		return sb.append(".").append(sourceName).toString();
	}
	
}
